package com.example.fan.airline_reservation.fragment_class;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.example.fan.airline_reservation.AC_Interface;
import com.example.fan.airline_reservation.Adapter.TripAdapter;
import com.example.fan.airline_reservation.Model.Fight;
import com.example.fan.airline_reservation.Model.Order;
import com.example.fan.airline_reservation.Model.Temp;
import com.example.fan.airline_reservation.Model.TicketList;
import com.example.fan.airline_reservation.Model.Trip;
import com.example.fan.airline_reservation.Model.USER;
import com.example.fan.airline_reservation.R;
import com.example.fan.airline_reservation.Sign_in;
import com.example.fan.airline_reservation.Traveler_Interface;

import org.json.JSONArray;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobQueryResult;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.QueryListener;
import cn.bmob.v3.listener.SQLQueryListener;

public class traveler_trip extends Fragment {

    USER user;
    List<Fight> fightList=new ArrayList<Fight>();
    List<Order> Orderlist=new ArrayList<Order>();
    List<Temp> tempList=new ArrayList<Temp>();
    String n;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.acitivity_traveler_trip,container,false);
        Bundle bundle=new Bundle();
        bundle=getArguments();
        user= (USER) bundle.getSerializable("USER11");
        Bmob.initialize(getContext(), "0802cbf346296dc9fac5a477f911ba39");
        n=user.getName();
        getOrder(n);
        FloatingActionButton fab1=(FloatingActionButton)view.findViewById(R.id.fabFresh);
        fab1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getOrder(n);
            }
        });
        return view;
    }

    public void getOrder(String name){
        BmobQuery<Order> bmobQuery=new BmobQuery<Order>();
        String bq1="select * from Order where account='"+name+"' order by fight";
        new BmobQuery<Order>().doSQLQuery(bq1, new SQLQueryListener<Order>() {
            @Override
            public void done(BmobQueryResult<Order> bmobQueryResult, BmobException e) {
                if(e==null){
                    Orderlist=bmobQueryResult.getResults();
                    List<Temp> t=new ArrayList<Temp>();
                    for(Order o:Orderlist){
                        Temp temp=new Temp();
                        temp.setFlightNO(o.getFight());
                        temp.setPassenger(o.getpName());
                        temp.setDate(o.getDate().getTime());
                        temp.setObjectId(o.getObjectId());
                        temp.setPick(o.isTicketCollect());
                        temp.setAccount(o.getAccount());
                        temp.setPrice(o.getPrice());
                        temp.setOrder(o);
                        t.add(temp);
                    }
                    Message message=handler.obtainMessage();
                    message.what=0;
                    message.obj=t;
                    handler.sendMessage(message);
                }
                else{
                }
            }
        });
    }
    private Handler handler=new Handler(){
        public void handleMessage(Message msg){
            switch (msg.what){
                case 0:
                    tempList=(List<Temp>)msg.obj;
                    getFlight();
                    break;


                case 1:
                    fightList=(List<Fight>) msg.obj;
                    getTrip();
                    break;

            }
        }
    };


    private  void getFlight(){
        String bq1="select * from Fight where";
        if(tempList.size()==0){
            List<Trip> t=new ArrayList<>();
            Toast.makeText(getActivity(),"该账户暂无订票信息",Toast.LENGTH_SHORT).show();
            ListView listView=(ListView)getActivity().findViewById(R.id.list_trip);
            TripAdapter tripAdapter=new TripAdapter(getActivity(),R.layout.trip_item,t);
            listView.setAdapter(tripAdapter);
        }
        else {
            for(int i=0;i<tempList.size();i++){
                Temp t=tempList.get(i);
                if(i+1==tempList.size()){
                    bq1=bq1+" FLIGHT='"+t.getFlightNO()+"' order by FLIGHT";
                }
                else {
                    bq1=bq1+" FLIGHT='"+t.getFlightNO()+"' or";
                }
            }

            Log.e("sql",bq1);
            new BmobQuery<Fight>().doSQLQuery(bq1, new SQLQueryListener<Fight>() {
                @Override
                public void done(BmobQueryResult<Fight> bmobQueryResult, BmobException e) {
                    if(e==null){
                        List<Fight> f=bmobQueryResult.getResults();
                        Message message=handler.obtainMessage();
                        message.what=1;
                        message.obj=f;
                        handler.sendMessage(message);
                    }
                    else {

                    }
                }
            });
        }
    }

    private void getTrip(){
        int tempI=0;
        List<Trip>  Triplist= new ArrayList<Trip>();
        for(Temp temp1:tempList){
            for(int i=0;i<fightList.size();i++){
                Fight ft=fightList.get(i);
                if(ft.getFLIGHT().equals(temp1.getFlightNO())){
                    tempI=i;
                    break;
                }
            }
            Trip trip=new Trip();
            trip.setObjectidOr(temp1.getObjectId());
            trip.setStartplace(fightList.get(tempI).getFROM()+fightList.get(tempI).getFROMNAME());
            trip.setArriveplace(fightList.get(tempI).getTO()+fightList.get(tempI).getTONAME());
            trip.setStarttime(getTime(fightList.get(tempI).getDATE()));
            trip.setArrivetime(getTime(fightList.get(tempI).getTODATE()));
            trip.setDate(getMidTime(fightList.get(tempI).getDATE()));
            trip.setFlightNO(fightList.get(tempI).getFLIGHT());
            Date a=fightList.get(tempI).getDATE();
            Date b=fightList.get(tempI).getTODATE();
            trip.setFlytime(getFlytime(a,b));
            trip.setAccount(temp1.getAccount());
            trip.setPassenger(temp1.getPassenger());
            trip.setPrice(temp1.getPrice());
            trip.setPick(temp1.isPick());
            trip.setOrder(temp1.getOrder());
            trip.setUser(user);
            if(fightList.get(tempI).getCurrentState()==0){
                trip.setState("正常候机");
            }
            else if(fightList.get(tempI).getCurrentState()==1){
                trip.setState("航班延误");
                trip.setDelaytime(fightList.get(tempI).getDelayTime());
            }
            else {
                trip.setState("航班取消");
            }
            Triplist.add(trip);
        }
        ListView listView=(ListView)getActivity().findViewById(R.id.list_trip);
        TripAdapter tripAdapter=new TripAdapter(getActivity(),R.layout.trip_item,Triplist);
        listView.setAdapter(tripAdapter);
    }

    private String getTime(Date source){
        String date=new String();
        Calendar calendar=Calendar.getInstance();
        calendar.setTime(source);
        int Hour=calendar.get(Calendar.HOUR_OF_DAY);
        int Minute=calendar.get(Calendar.MINUTE);
        date=Hour+":"+Minute;
        return date;
    }
    private String getMidTime(Date source){
        String date=new String();
        Calendar calendar=Calendar.getInstance();
        calendar.setTime(source);
        int Year=calendar.get(Calendar.YEAR);
        int Month=calendar.get(Calendar.MONTH)+1;
        int Day=calendar.get(Calendar.DAY_OF_MONTH);
        date=Year+"年"+Month+"月"+Day+"日";
        return date;
    }
    private String getMoreTime(Date source) {
        String date=new String();
        Calendar calendar=Calendar.getInstance();
        calendar.setTime(source);
        int Hour=calendar.get(Calendar.HOUR_OF_DAY);
        int Minute=calendar.get(Calendar.MINUTE);
        int Second=calendar.get(Calendar.SECOND);
        int Year=calendar.get(Calendar.YEAR);
        int Month=calendar.get(Calendar.MONTH)+1;
        int Day=calendar.get(Calendar.DAY_OF_MONTH);
        date=Year+"-"+Month+"-"+Day+" "+Hour+":"+Minute+":"+Second;
        return date;
    }
    private String getFlytime(Date source1,Date source2){
        String Flytime=new String();
        String sou1=getMoreTime(source1);
        String sou2=getMoreTime(source2);
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try
        {
            Date d1 = df.parse(sou1);
            Date d2 = df.parse(sou2);
            long diff = d2.getTime() - d1.getTime();//这样得到的差值是微秒级别
            long days = diff / (1000 * 60 * 60 * 24);
            long hours = (diff-days*(1000 * 60 * 60 * 24))/(1000* 60 * 60);
            long minutes = (diff-days*(1000 * 60 * 60 * 24)-hours*(1000* 60 * 60))/(1000* 60);
            Flytime=days+"天"+hours+"小时"+minutes+"分";
        }catch (Exception e)
        {
        }
        return Flytime;
    }
}
